import { observable, computed, action } from 'mobx'
import { StoreModule } from '@/utils/mobx-store'
import { getEggCookieToken } from '@/utils'
import { apiLogin, apiAutoLogin, apiSignUp, apiLogout, apiUpdateInfo } from '@/apis/user'

const initInfo = {
  _id: null, // 数据库生成
  username: '',
  password: '',
  nickname: '',
  avatar: '',
  gender: 'unknow',
  cv: '',
  desc: '',
}

class UserStore extends StoreModule {
  @observable info = { ...initInfo }

  @computed
  get isLogin() {
    const token = getEggCookieToken()
    return token && this.info._id
  }

  @action autoLogin = async () => {
    const info = await apiAutoLogin()
    this.$set({ info })
  }

  @action
  login = async ({ username = '', password = '' }) => {
    const info = await apiLogin({ username, password })
    this.$set({ info })
  }

  @action
  signUp = async (params = {}) => {
    const { username = '', password = '' } = params
    await apiSignUp(params)
    await this.login({ username, password })
  }

  @action
  logout = async () => {
    await apiLogout()
    this.$set({ info: initInfo })
  }

  @action
  update = async (params = {}) => {
    await apiUpdateInfo(params)
    await this.autoLogin()
  }
}

export default new UserStore()
